package com.feature.core.util;

import java.io.ByteArrayInputStream;
import java.util.Optional;

import org.apache.commons.codec.digest.DigestUtils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.PutObjectRequest;
import com.feature.core.config.properties.AliyunOssProperties;

public class AliyunOssUtil {
    private static OSS ossClient = SpringContextUtil.getBean(OSS.class);
    private static AliyunOssProperties ossProperties = SpringContextUtil.getBean(AliyunOssProperties.class);

    public static String uploadImage(byte[] data, String fileName) {
        return uploadImage(data, fileName, DigestUtils.md5Hex(data));
    }

    public static String uploadImage(byte[] data, String fileName, String md5) {
        String suffix = Optional.ofNullable(fileName).filter(v -> v.contains(".")).map(v -> v.substring(v.lastIndexOf("."))).orElse(".png");
        String objectName = "image/" + md5 + suffix;
        PutObjectRequest putObjectRequest = new PutObjectRequest(ossProperties.getBucket(), objectName, new ByteArrayInputStream(data));
        ossClient.putObject(putObjectRequest);
        return "https://" + ossProperties.getBucket() + ".oss-" + ossProperties.getRegion() + ".aliyuncs.com/" + objectName;
    }

}
